package com.feng.gulimall.product.service.impl;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;
import com.feng.gulimall.product.dao.CategoryDao;
import com.feng.gulimall.product.entity.CategoryEntity;
import com.feng.gulimall.product.service.CategoryBrandRelationService;
import com.feng.gulimall.product.service.CategoryService;
import com.feng.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查出所有分类
        List<CategoryEntity> entities = categoryDao.selectList(null);
        //2.组成成父子的树形结构
        //2.1) 找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter((e) -> (e.getParentCid() == 0)

        ).map((menu)->{
            menu.setChildren(getChildrens(menu,entities));
            return menu;
        }).sorted((c,d)->{
            return(c.getSort()==null?0:c.getSort())-(d.getSort()==null?0:d.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 1.检查当前删除的菜单，是否被别的地方引用

        categoryDao.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths=new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        //需要将其逆序
        Collections.reverse(parentPath);
        return  parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有数据
     * @param category
     */
    @Override
    @Caching(evict = {
            @CacheEvict(value = "category",key="'getLevel1Category'")
            ,@CacheEvict(value = {"category"},key="'getCatalogJson'")
    })
    @Transactional

    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());

    }
    //每一个需要缓存的数据我们都要来指定放到那个名字的缓存【缓存的分区（安装业务类型
    @Cacheable(value = {"category"},key="#root.method.name",sync = true)  //代表当前方法的结果需要缓存，如果缓存中有，方法不用调用，如果缓存没有，调用方法，查出来将方法结果放入缓存
    @Override
    public List<CategoryEntity> getLevel1Category() {
        System.out.println("getLevel1Category()");
        LambdaQueryWrapper<CategoryEntity> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(CategoryEntity::getParentCid,0);
        List<CategoryEntity> list = this.list(queryWrapper);
        return list;
    }
    //TODO 产生堆外内存溢出:OutofDirectMemoryError

    @Override
    @Cacheable(value = "category",key="#root.methodName",sync = true)
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        System.out.println("查询了数据库");

        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));

        return parentCid;
    }

    //    @Override
    public  Map<String, List<Catelog2Vo>> getCatalogJson2() {
        //1.加入缓存逻辑
        String catalogjson = stringRedisTemplate.opsForValue().get("catalogjson");
        if(StringUtils.isEmpty(catalogjson)){
            //为空，查询数据库
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLocalLock();

            return catalogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> catalogJsonFromDb=JSON.parseObject(catalogjson,new TypeReference<Map<String, List<Catelog2Vo>>>(){});

        return catalogJsonFromDb;



    }

    public  Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLocalLock()  {
        //1.占分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid,300,TimeUnit.SECONDS);
        Map<String, List<Catelog2Vo>> dataFromDb;
        if(lock==true){
            System.out.println("获取分布式锁成功");
            //枷锁成功，返回业务
            try{
                dataFromDb= getDataFromDb();
            }
            finally {
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                //删除锁
                stringRedisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }

            //删除锁
            //获取值对比，对比成功删除=原子操作才可以 lua脚本解锁
//            String uuids = stringRedisTemplate.opsForValue().get("lock");
//            if(uuids.equals(uuid)){
//                //删除自己的锁
//                stringRedisTemplate.delete("lock");
//            }


            return dataFromDb;
        }else{
            //枷锁失败...重试
            //休眠100ms
            System.out.println("获取分布式锁失败，等待重试");
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLocalLock();//自旋的方式
        }


    }
    public  Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLocalLock()  {
        //1.占分布式锁，去redis占坑


        RLock lock = redissonClient.getLock("CatalogJson-lock");
        System.out.println("获取分布式锁成功");
        lock.lock();
            //枷锁成功，返回业务
        Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
              lock.unlock();
            }

            //删除锁
            //获取值对比，对比成功删除=原子操作才可以 lua脚本解锁
//            String uuids = stringRedisTemplate.opsForValue().get("lock");
//            if(uuids.equals(uuid)){
//                //删除自己的锁
//                stringRedisTemplate.delete("lock");
//            }


            return dataFromDb;



    }



    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        //得到锁应该先去去缓存中确定一次，如果没有才查询
        String catalogjson = stringRedisTemplate.opsForValue().get("catalogjson");
        if (!StringUtils.isEmpty(catalogjson)) {
            //缓存不为空
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = JSON.parseObject(catalogjson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });

            return catalogJsonFromDb;
        }
        System.out.println("查询了数据库");

        //将数据库的多次查询变为一次
        List<CategoryEntity> selectList = this.baseMapper.selectList(null);

        //1、查出所有分类
        //1、1）查出所有一级分类
        List<CategoryEntity> level1Categorys = getParent_cid(selectList, 0L);

        //封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //1、每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());

            //2、封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName().toString());

                    //1、找当前二级分类的三级分类封装成vo
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());

                    if (level3Catelog != null) {
                        List<Catelog2Vo.Category3Vo> category3Vos = level3Catelog.stream().map(l3 -> {
                            //2、封装成指定格式
                            Catelog2Vo.Category3Vo category3Vo = new Catelog2Vo.Category3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());

                            return category3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(category3Vos);
                    }

                    return catelog2Vo;
                }).collect(Collectors.toList());
            }

            return catelog2Vos;
        }));
        //查到的数据放入缓存,将查出来的对象转为json放在缓存中
        String s = JSON.toJSONString(parentCid);
        stringRedisTemplate.opsForValue().set("catalogjson", s);
        return parentCid;
    }


    public  Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        synchronized (this){
            //得到锁应该先去去缓存中确定一次，如果没有才查询
            return getDataFromDb();
        }


    }
    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList,Long parentCid) {
        List<CategoryEntity> categoryEntities = selectList.stream().filter(item -> item.getParentCid().equals(parentCid)).collect(Collectors.toList());
        return categoryEntities;
        // return this.baseMapper.selectList(
        //         new QueryWrapper<CategoryEntity>().eq("parent_cid", parentCid));
    }


    private List<Long> findParentPath(Long catelogId,List<Long> paths){
        //1.收集当前结点id
        paths.add(catelogId);
        CategoryEntity byId=this.getById(catelogId);
        if(byId.getParentCid()!=0){
            findParentPath(byId.getParentCid(),paths);
        }
        return paths;
    }

    /**
     *
     * @param categoryEntity 当前查询菜单的数据
     * @param all 整个菜单的集合
     * @return
     */
    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity categoryEntity, List<CategoryEntity> all){
        List<CategoryEntity> collect = all.stream().filter(a -> {
            return a.getParentCid()==categoryEntity.getCatId();
        }).map(b->{
            //1.找到子菜单
            b.setChildren(getChildrens(b,all));
            return b;
        }).sorted((c,d)->{
            //2.菜单的排序
            return (c.getSort()==null?0:c.getSort())-(d.getSort()==null?0:d.getSort());
        }).collect(Collectors.toList());


        return collect;

    }

}
